package api

import (
	"lgb24kcs.com/im/internal/model"
	"lgb24kcs.com/im/internal/service"
	"lgb24kcs.com/im/utils"
	"log"
	"net/http"
	"sync"

	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
)

var (
	clients  = make(map[string]*websocket.Conn) // 用户ID -> WebSocket 连接
	mu       sync.Mutex
	upgrader = websocket.Upgrader{
		// ReadBufferSize:  1024,
		// WriteBufferSize: 1024,
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
	}
)

//// AddClient 添加用户websocket 连接
//func AddClient(userID string, conn *websocket.Conn) {
//	mu.Lock()
//	clients[userID] = conn // 添加用户ID和WebSocket连接到映射中
//
//	defer mu.Unlock()
//}
//
//// RemoveClient 移除用户websocket连接
//func RemoveClient(userID string) {
//	mu.Lock()
//	delete(clients, userID)
//	defer mu.Unlock()
//
//}
//
//// GetClient 获取用户websocket连接
//
//func GetClient(userID string) *websocket.Conn {
//	mu.Lock()
//
//	defer mu.Unlock()
//
//	return clients[userID]
//
//}

func HandleWebSocket(ctx *gin.Context) {

	userID := ctx.Query("user_id")
	conn, err := upgrader.Upgrade(ctx.Writer, ctx.Request, nil)
	if err != nil {
		log.Println(err.Error())
		return
	}
	defer conn.Close()
	// 添加连接
	mu.Lock()
	//clients[userID] = conn
	utils.AddClient(userID, conn) // 添加连接
	mu.Unlock()

	log.Printf("用户%s 连接成功\n", userID)
	// 监听消息
	for {
		var msg model.Message

		err = conn.ReadJSON(&msg)
		if err != nil {
			log.Println(err.Error())
			break

		}
		// 处理消息
		service.HandleMessage(msg)
	}

	// 连接关闭时删除
	mu.Lock()
	delete(clients, userID)
	mu.Unlock()
	log.Println("用户 %s 断开连接", userID)

}
